package com.gcxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gcxy.constant.StringConst;
import com.gcxy.core.PageVO;
import com.gcxy.dto.score.StudentScoreDTO;
import com.gcxy.dto.score.StudentScorePageDTO;
import com.gcxy.dto.evaluate.UpdateEvaluateDTO;
import com.gcxy.entity.Evaluate;
import com.gcxy.entity.Semester;
import com.gcxy.entity.Weekly;
import com.gcxy.mapper.EvaluateMapper;
import com.gcxy.mapper.WeeklyMapper;
import com.gcxy.service.EvaluateService;
import com.gcxy.service.SemesterService;
import com.gcxy.service.WeeklyService;
import com.gcxy.vo.score.ScoreVO;
import com.gcxy.vo.score.StudentScorePageVO;
import com.gcxy.vo.score.StudentScoreVO;
import com.gcxy.vo.teacher.TeacherPageVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 评价表（教师评价、学生自我评价记录表） 服务实现类
 * </p>
 *
 * @author Huang先森
 * @since 2024-07-22
 */
@Slf4j
@Service
public class EvaluateServiceImpl extends ServiceImpl<EvaluateMapper, Evaluate> implements EvaluateService {

    @Autowired
    private WeeklyService weeklyService;

    @Autowired
    private SemesterService semesterService;
    @Autowired
    private EvaluateMapper evaluateMapper;
    @Autowired
    private WeeklyMapper weeklyMapper;

    /**
     * 根据周报id获取对应的评价信息
     *
     * @param weeklyId
     * @return
     */
    @Override
    public Evaluate getByWeeklyId(Integer weeklyId) {
        LambdaQueryWrapper<Evaluate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Evaluate::getWeeklyId, weeklyId);
        return getOne(queryWrapper);
    }

    /**
     * 新增评价信息
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public void addEvaluate(Integer agencyId) {
        Semester semester = semesterService.getCurrentSemester();
        if (ObjectUtils.isEmpty(semester)) {
            throw new RuntimeException("组织{" + agencyId + "}当前时间不需要生成周评价表");
        }
        List<Weekly> weeklyList = weeklyService.getWeeklyList(semester.getId(), agencyId);
        if (CollectionUtils.isEmpty(weeklyList)) {
            throw new RuntimeException("组织{" + agencyId + "}新增评价表失败-根据学期id和机构id未能找到当前周对应的周报");
        }
        for (Weekly weekly : weeklyList) {
            Evaluate weeklyEvaluate = getByWeeklyId(weekly.getId());
            Evaluate evaluate = new Evaluate();
            evaluate.setWeeklyId(weekly.getId());
            evaluate.setPracticalTeacher(weekly.getPracticalTeacherId());
            evaluate.setHonoraryTeacher(weekly.getHonoraryTeacherId());
            evaluate.setUpdater(StringConst.INITIALIZE_UPDATE_ADMIN);
            if (ObjectUtils.isNotEmpty(weeklyEvaluate)) {
                continue;
            } else {
                boolean save = save(evaluate);
                if (!save) {
                    throw new RuntimeException("组织{" + agencyId + "}新增评价表失败");
                } else {
                    log.info("新增评价表成功");
                }
            }
        }
    }


    /**
     * 修改评价信息
     *
     * @param updateEvaluateDTO
     * @return
     */
    @Override
    public boolean updateEvaluate(UpdateEvaluateDTO updateEvaluateDTO) {
        Evaluate evaluate = getById(updateEvaluateDTO.getId());
        if (ObjectUtils.isEmpty(evaluate)) {
            log.error("修改评价表失败-根据id未能找到对应的评价表");
            return false;
        }
        BeanUtils.copyProperties(updateEvaluateDTO, evaluate);
        return updateById(evaluate);
    }

    /**
     * 根据条件分页查询学生成绩
     *
     * @param studentScorePageDTO
     * @return
     */
    @Override
    public PageVO<StudentScorePageVO> getStudentScorePageByCondition(StudentScorePageDTO studentScorePageDTO) {
        PageVO<StudentScorePageVO> studentScoreVOPageVO = new PageVO<>(studentScorePageDTO.getPageNo().longValue(), studentScorePageDTO.getPageSize().longValue());
        List<StudentScorePageVO> studentScoreVOList = evaluateMapper.getStudentScorePageByCondition(studentScorePageDTO);
        if (!CollectionUtils.isEmpty(studentScoreVOList)) {
            studentScoreVOList.stream().forEach(studentScoreVO -> {
                List<String> teacherNameList = evaluateMapper.getTeacherListByStudentNumber(studentScoreVO.getStudentNumber());
                if (CollectionUtils.isNotEmpty(teacherNameList) && teacherNameList.size() > 1) {
                    String teacherNames = "";
                    for (int i = 0; i < teacherNameList.size(); i++) {
                        if (i == teacherNameList.size() - 1) {
                            teacherNames += teacherNameList.get(i);
                        } else {
                            teacherNames += teacherNameList.get(i) + "、";
                        }
                    }
                    studentScoreVO.setHonoraryTeacherName(teacherNames);
                } else {
                    studentScoreVO.setHonoraryTeacherName(teacherNameList.get(0));
                }
            });
        } else {
            studentScoreVOPageVO.setTotal(0L);
            studentScoreVOPageVO.setPages(0L);
            studentScoreVOPageVO.setRecords(studentScoreVOList);
            return studentScoreVOPageVO;
        }
        if (ObjectUtils.isNotEmpty(studentScorePageDTO.getStudentNumber())) {
            //从集合总根据过滤出能和参数学号模糊匹配的数据
            studentScoreVOList = studentScoreVOList.stream()
                    .filter(studentScoreVO -> studentScoreVO.getStudentNumber().contains(studentScorePageDTO.getStudentNumber()))
                    .collect(Collectors.toList());
        }
        if (ObjectUtils.isNotEmpty(studentScorePageDTO.getStudentName())) {
            //从集合总根据过滤出能和参数学号模糊匹配的数据
            studentScoreVOList = studentScoreVOList.stream()
                    .filter(studentScoreVO -> studentScoreVO.getStudentName().contains(studentScorePageDTO.getStudentName()))
                    .collect(Collectors.toList());
        }
        studentScoreVOPageVO.setTotal(Long.valueOf(studentScoreVOList.size()));
        studentScoreVOList = studentScoreVOList.stream()
                .skip((long) (studentScorePageDTO.getPageNo() - 1) * studentScorePageDTO.getPageSize()) // 跳过前面的元素
                .limit(studentScorePageDTO.getPageSize()) // 限制结果集的大小
                .collect(Collectors.toList()); // 收集结果到一个新的列表

        studentScoreVOPageVO.setRecords(studentScoreVOList);
        Long pages = studentScoreVOPageVO.getTotal() % studentScorePageDTO.getPageSize() == 0 ? studentScoreVOPageVO.getTotal() / studentScorePageDTO.getPageSize() : studentScoreVOPageVO.getTotal() / studentScorePageDTO.getPageSize() + 1;
        studentScoreVOPageVO.setPages(pages);
        return studentScoreVOPageVO;
    }

    /**
     * 根据条件查询学生成绩详情
     *
     * @param studentScoreDTO
     * @return
     */
    @Override
    public StudentScoreVO getStudentScoresByCondition(StudentScoreDTO studentScoreDTO) {
        StudentScoreVO studentScoreVO = new StudentScoreVO();
        studentScoreVO.setStudentName(studentScoreDTO.getStudentName());
        studentScoreVO.setStudentNumber(studentScoreDTO.getStudentNumber());
        studentScoreVO.setScoreVOList(evaluateMapper.getScoreListByCondition(studentScoreDTO));
        return studentScoreVO;
    }
}
